<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\BaseController;
use Swoole\Coroutine\Channel;
use Co;

class TestController extends BaseController {

    public function testWorkerman() {
        $c = new Channel(2);
        $this->channelC($c);
        $this->channelU($c);
        return json_encode([
            "status" => 200,
            "data" => "Hello world",
            "message" => "꒰ᐢ⸝⸝•༝•⸝⸝ᐢ꒱"
        ]);
    }

    private function channelC(Channel $c) {
        go(function () use ($c) {
            $flag = true;
            for($i = 100;$i && $flag;) {
                $result = $c->push($i--);
                if($result === false) {
                    echo "通道已关闭", PHP_EOL;
                    $flag = false;
                }else {
                    Co::sleep(rand(1,4));
                }
            }
        });
    }

    private function channelU(Channel $c) {
        go(function () use ($c) {
            $flag = true;
            for(;$flag;){
                $i = $c->pop(3.0);
                if($i === false) {
                    echo "超时", PHP_EOL;
                    $flag = false;
                    $c->close();
                }else {
                    echo $i, PHP_EOL;
                }
            }
        });
    }
}
